from decimal import Decimal
from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from .serializer import OrderSKUSerializer, OrderCreateSerializer
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated

# Create your views here.


class OrderView(APIView):
    """订单结算"""

    def get(self, request):

        # 获取当前用户
        user = request.user
        # 获取redis中勾选的商品
        conn = get_redis_connection('cart')
        # 当前用户的所有商品的id {‘sku_id’:count}
        redis_cart = conn.hgetall('cart_%s' % user.id)
        cart_selected = conn.smembers('selected_cart_%s' % user.id)

        # 商品的数量
        cart = {}
        # 取出勾选的数据
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 输出商品信息
        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        # 序列化输出
        ser = OrderSKUSerializer({'freight': freight, 'skus': skus})

        return Response(ser.data)


class OrderCreateView(CreateAPIView):
    """创建，保存订单"""
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCreateSerializer